package com.example.netty.tcp.codec;

import com.example.netty.tcp.message.BaseMessage;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

public class JsonEncoder extends MessageToByteEncoder<BaseMessage> {
    private static final Logger logger = LoggerFactory.getLogger(JsonEncoder.class);
    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    protected void encode(ChannelHandlerContext ctx, BaseMessage msg, ByteBuf out) throws Exception {
        // 转换为JSON字符串（去除空白字符）
        String json = mapper.writeValueAsString(msg).replaceAll("\\s+", "");
        logger.debug("发送JSON消息: {}", json);

        // 直接写入JSON字节数组（无长度字段）
        byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
        out.writeBytes(bytes);
    }
}
